﻿using DAL.Vo;
using ERP.Common.Util;
using ERP.Common.Util.Util.Model;
using ERP.SYS.Interfaces;
using ERP.SYS.Model.Entity;
using Microsoft.AspNetCore.Mvc;

namespace ERP.SYS.Controller.Controllers;

[Route("api/[controller]")]
[ApiController]
public class LoginController : ControllerBase
{
    private readonly IMenuService _userService;
    private readonly IRoleService _roleService;

    public LoginController(IMenuService userService, IRoleService roleService)
    {
        _userService = userService;
        _roleService = roleService;
    }

    [HttpPost]
    public async Task<IActionResult> Login([FromBody] SysUser user)
    {
        if (string.IsNullOrEmpty(user.Name) || string.IsNullOrEmpty(user.Password))
        {
            return BadRequest("Invalid username or password");
        }

        var tempUserEntity = await _roleService.SelectUserRoleByNameAndPassword(user.Name, user.Password);

        if (tempUserEntity == null)
        {
            return BadRequest("User not found");
        }

        LoginVO loginVO = new LoginVO { Authentication = JwtUtil.CreateJwt(tempUserEntity.UserId, tempUserEntity.User.Name, tempUserEntity.RoleId) };

        return Ok(RestResultBuilder<LoginVO>.Success(loginVO));
    }
}
